package org.example.myspringbootproject01.controller;

import org.example.myspringbootproject01.entity.Student;
import org.example.myspringbootproject01.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    // 获取所有学生（支持排序）
    @GetMapping
    public List<Student> getAllStudents( @RequestParam(required = false) String sortField,  @RequestParam(required = false) String sortOrder) {

        List<Student> students = studentRepository.findAll();

        if (sortField != null && sortOrder != null) {
            Comparator<Student> comparator = getStudentComparator(sortField, sortOrder);
            if (comparator != null) {
                students.sort(comparator);
            }
        }

        return students;
    }
    // 根据字段和排序方向获取比较器
    private Comparator<Student> getStudentComparator(String sortField, String sortOrder) {
        Comparator<Student> comparator = null;
        boolean isDesc = "desc".equalsIgnoreCase(sortOrder);

        switch (sortField.toLowerCase()) {
            case "studentid":
                comparator = isDesc ? Comparator.comparing(Student::getStudentId).reversed()
                        : Comparator.comparing(Student::getStudentId);
                break;
            case "birthdate":
                comparator = isDesc ? Comparator.comparing(Student::getBirthDate).reversed()
                        : Comparator.comparing(Student::getBirthDate);
                break;
            default:
                break;
        }

        return comparator;
    }


    // 创建学生
    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentRepository.save(student);
    }

    // 获取单个学生
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
        Optional<Student> student = studentRepository.findById(id);
        return student.map(ResponseEntity::ok)
                     .orElse(ResponseEntity.notFound().build());
    }

    // 更新学生
    @PutMapping("/{id}")
    public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student studentDetails) {
        return studentRepository.findById(id)
                .map(student -> {
                    student.setName(studentDetails.getName());
                    student.setStudentId(studentDetails.getStudentId());
                    student.setGender(studentDetails.getGender());
                    student.setBirthDate(studentDetails.getBirthDate());
                    student.setClassName(studentDetails.getClassName());
                    student.setMajor(studentDetails.getMajor());
                    student.setPhone(studentDetails.getPhone());
                    student.setEmail(studentDetails.getEmail());
                    Student updatedStudent = studentRepository.save(student);
                    return ResponseEntity.ok(updatedStudent);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteStudent(@PathVariable Long id) {
        System.out.println("尝试删除ID为: " + id);  // 添加日志
        return studentRepository.findById(id).map(student -> {
                    System.out.println("找到学生: " + student.getName());  // 添加日志
                    studentRepository.delete(student);
                    return ResponseEntity.ok().build();
                })
                .orElseGet(() -> {
                    System.out.println("未找到ID为 " + id + " 的学生");  // 添加日志
                    return ResponseEntity.notFound().build();
                });
    }

    // 文件上传接口
    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("studentId") String studentId) {  // 添加学生ID参数

        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的文件");
            }

            String originalFilename = file.getOriginalFilename();
            long fileSize = file.getSize();

            if (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png")) {
                return ResponseEntity.badRequest().body("仅支持JPG和PNG格式图片");
            }

            if (fileSize > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest().body("文件大小不能超过5MB");
            }

            System.out.println("查找学生ID: " + studentRepository.findByStudentId(studentId));

            // 保存到数据库
            return studentRepository.findByStudentId(studentId)
                    .map(student -> {
                        try {
                            student.setFileName(originalFilename);
                            student.setFileType(file.getContentType());
                            student.setFileData(file.getBytes());
                            studentRepository.save(student);
                            return ResponseEntity.ok("文件上传成功并保存到数据库: " + originalFilename);
                        } catch (IOException e) {
                            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                    .body("文件处理失败: " + e.getMessage());
                        }
                    })
                    .orElse(ResponseEntity.notFound().build());

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件上传失败: " + e.getMessage());
        }
    }

    // 音频上传接口
    @PostMapping("/uploadFileAudio")
    public ResponseEntity<String> handleAudioUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("studentId") String studentId) {

        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的音频文件");
            }

            String originalFilename = file.getOriginalFilename();
            long fileSize = file.getSize();

            // 修改为支持音频格式
            if (!originalFilename.endsWith(".mp3") && !originalFilename.endsWith(".wav")) {
                return ResponseEntity.badRequest().body("仅支持MP3和WAV格式音频");
            }

            if (fileSize > 10 * 1024 * 1024) {  // 增大到10MB限制
                return ResponseEntity.badRequest().body("音频文件大小不能超过10MB");
            }

            // 保存到数据库
            return studentRepository.findByStudentId(studentId)
                    .map(student -> {
                        try {
                            student.setAudioFileName(originalFilename);
                            student.setAudioFileType(file.getContentType());
                            student.setAudioFileSize(fileSize);
                            student.setAudioData(file.getBytes());
                            studentRepository.save(student);
                            return ResponseEntity.ok("音频上传成功并保存到数据库: " + originalFilename);
                        } catch (IOException e) {
                            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                    .body("音频处理失败: " + e.getMessage());
                        }
                    })
                    .orElse(ResponseEntity.notFound().build());

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("音频上传失败: " + e.getMessage());
        }
    }

    // 音频上传接口
    @PostMapping("/uploadFileVideo")
    public ResponseEntity<String> handleVideoUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("studentId") String studentId) {

        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的视频文件");
            }

            String originalFilename = file.getOriginalFilename();
            long fileSize = file.getSize();

            // 支持常见视频格式
            if (!originalFilename.endsWith(".mp4") && !originalFilename.endsWith(".mov")
                && !originalFilename.endsWith(".avi")) {
                return ResponseEntity.badRequest().body("仅支持MP4、MOV和AVI格式视频");
            }

            if (fileSize > 20 * 1024 * 1024) {  // 视频文件限制为20MB
                return ResponseEntity.badRequest().body("视频文件大小不能超过20MB");
            }

            // 保存到数据库
            return studentRepository.findByStudentId(studentId)
                    .map(student -> {
                        try {
                            student.setVideoFileName(originalFilename);
                            student.setVideoFileType(file.getContentType());
                            student.setVideoFileSize(fileSize);
                            student.setVideoData(file.getBytes());
                            studentRepository.save(student);
                            return ResponseEntity.ok("视频上传成功并保存到数据库: " + originalFilename);
                        } catch (IOException e) {
                            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                    .body("视频处理失败: " + e.getMessage());
                        }
                    })
                    .orElse(ResponseEntity.notFound().build());

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("视频上传失败: " + e.getMessage());
        }
    }
}

